
import re
import pandas as pd
from itertools import chain
from battery_cycle_qa_generator import BatteryCycleQAGenerator
from cycle_data_processor import CycleDataProcessor
from battery_qa_generator.main import QAmain


def main():
    '''读取数据'''
    data_file_paths = [
        '../data/硬碳循环.xlsx',
        '../data/硬碳倍率.xlsx',
        'data\氧化物软包循环.xlsx'
    ]

    for idx, file_path in enumerate(data_file_paths):
        if idx != 2:
            continue

        sheet_name = "cycle"
        cycle_data = pd.read_excel(file_path, sheet_name = sheet_name)
        
        sheet_name = "test"
        test_data = pd.read_excel(file_path, sheet_name = sheet_name)

        sheet_name = "step"
        step_data = pd.read_excel(file_path, sheet_name = sheet_name)

        sheet_name = "record"
        record_data = pd.read_excel(file_path, sheet_name = sheet_name)

        test_data = pd.DataFrame(test_data)
        cycle_data = pd.DataFrame(cycle_data)
        step_data = pd.DataFrame(step_data)
        record_data = pd.DataFrame(record_data)
        
        # 展平嵌套列表 , 因为cycle_index是二维列表
        flattened_data = list(chain.from_iterable(_extract_cycle_indeices(test_data)))

        #将展平后的列表元素转换为整数
        cycle_group_indices = list(map(int, flattened_data))   

        data_processor = CycleDataProcessor(cycle_data, cycle_group_indices)
        cycle_data = data_processor.Calling()

        #按不同倍率拆分
        #divide_data = cycle_split_data(processed_cycle_data, cycle_index)

        #删除第一行和最后一行
        #processed_cycle_data = cycle_data.iloc[1:-1]  
        

    file_path_jsonl = 'batllm_data_oxide_before100_lqy1.jsonl'
    with open(file_path_jsonl, 'w') as file:
        pass

    charge_discharge_rates, charge_discharge_currents = _get_charge_discharge_params(test_data)
    reactant_mass = _get_reactant_mass(test_data)

    qa_generator = QAmain(cycle_data, step_data, record_data, cycle_group_indices, charge_discharge_rates, charge_discharge_currents, reactant_mass)
    qa_generator.main()



def _get_reactant_mass(test_data):
    start_row, start_col = _locate_parameter_start(test_data, "活性物质")
    cell_value = str(test_data.iat[start_row, start_col + 2])
    numbers = re.findall(r'\d+', cell_value)
    numbers = int(numbers[0])
    return numbers


def _get_charge_discharge_params(test_data):
    '''[获取充放电参数]恒流充放电倍率和恒流充放电电流存储进数组'''

    #定位参数起始行
    judge = 0
    start_row, start_col = _locate_parameter_start(test_data, "恒流充电")

    #提取倍率和电流
    charge_discharge_rates = _extract_parameter_list(start_row, start_col + 3, test_data)
    
    charge_discharge_currents = _extract_parameter_list(start_row, start_col + 4, test_data)

    return charge_discharge_rates, charge_discharge_currents


def _extract_parameter_list(start_row, col, data):
    """[提取参数列表]从指定列提取参数列表(每2个为一组)"""
    param_list = []
    current_group = []

    for row in range(start_row, data.shape[0]):
        cell_value = data.iloc[row, col]
        if pd.notna(cell_value) and cell_value != "":
            current_group.append(cell_value)

        if len(current_group) == 2:
            param_list.append(current_group)
            current_group = []

    return param_list
 

# def cycle_split_data(data, cycle_index):
    # divide_data = []
    # start = 1
# 
    # for group_length in cycle_index:
        # end = start + group_length - 1
        # group = data[(data["循环号"] >= start) & (data["循环号"] <= end)]
        # divide_data.append(group)
        # start = end + 1
#  


def _extract_cycle_indeices(test_data):
    '''[提取循环索引]从text表单中提取循环次数分组索引'''
    cycle_group_indices = []
    target_col = 0
    
    for start_row in range(test_data.shape[0]):
        for col in range(test_data.shape[1]):
            cell_value = str(test_data.iat[start_row, col])
            if '循环次数' in cell_value and re.findall(r'\d+', cell_value):
                target_col = 1
                break

        if target_col:
            break

    for row in range(start_row, test_data.shape[0]):
        cell_value = str(test_data.iat[row, col])
        if '循环次数' in cell_value and re.findall(r'\d+', cell_value):
            numbers = re.findall(r'\d+', cell_value)
            if numbers and len(numbers) == 1:
                cycle_group_indices.append(numbers)

    return cycle_group_indices


def _locate_parameter_start(data, keyword):
    """[定位参数起始位置]定位参数表的起始行列"""
    for row in range(data.shape[0]):
        for col in range(data.shape[1]):
            if keyword in str(data.iloc[row, col]):
                return row, col
            
    raise ValueError(f"未找到关键字'{keyword}'")


if __name__ == "__main__":
    main()